//去除空格
String.prototype.Trim = function()
{
	return this.replace(/(^\s*)|(\s*$)/g, "");
} 
String.prototype.LTrim = function()
{ 
	return this.replace(/(^\s*)/g, "");
}
String.prototype.RTrim = function()
{ 
	return this.replace(/(\s*$)/g, "");
}

//随机数字
function getRandomDigital(n)
{
	var result = '';
	for(var i = 0; i < 4; i++)
	{
		var digital = Math.floor(Math.random() * n + 1);
		result += digital;
	}
	return result;
}


//验证提交数据是否符合条件
function validate()
{
	if (!notNullCheck()) {
		return false;
	}
	if (!notSpaceCheck()) {
		return false;
	}
	if (!digitalCheck()) {
		return false;
	}
    if (!emailCheck()) {
    	return false;
    }
    if (!letterCheck()) {
    	return false;
    }
    if (!lengthLimit()) {
    	return false;
    }
   
	return true;
}


//不能为空验证
function notNullCheck()
{
	var notNull = $('.notNull');
	var length = notNull.length;
	for(var i = 0; i < length; i++)
	{
		var nn = $(notNull.get(i));
		if('' == nn.val().Trim())
		{
			var title = nn.attr('title');
			showMsg(title + '不能为空!', function(){nn.focus()});
			return false;
		}
	}
	return true;
}

//不能有空格
function notSpaceCheck()
{
	var notSpace = $('.notSpace');
	var length = notSpace.length;
	for(var i = 0; i < length; i++)
	{
		var ns = $(notSpace.get(i));
		if(ns.val() != ns.val().Trim())
		{
			var title = ns.attr('title');
			showMsg(title + '不能有空格!', function(){ns.focus()});
			return false;
		}
	}
	return true;
}

//数字验证
function digitalCheck()
{
	var digital = $('.digital');
	var length = digital.length;
	for(var i = 0; i < length; i++)
	{
		var d = $(digital.get(i));
		var p = /^[0-9]*$/;
		if(!p.exec(d.val()))
		{
			var title = d.attr('title');
			showMsg(title + '只能是整数!', function(){d.focus()});
			return false;
		}
	}
	return true;
}

//字母验证
function letterCheck()
{
	var letter = $('.letter');
	var length = letter.length;
	for(var i = 0; i < length; i++)
	{
		var l = $(letter.get(i));
		var p = /^[a-zA-Z]*$/;
		if(!p.exec(l.val()))
		{
			var title = l.attr('title');
			showMsg(title + '只能是字母!', function(){l.focus()});
			return false;
		}
	}
	return true;
}

//验证email
function emailCheck(){
	var email = $('.email');
	var length = email.length;
	for(var i = 0; i < length; i++)
	{
		var e = $(email.get(i));
		var p =  /^([a-zA-Z0-9._-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/;
		if(!p.exec(e.val()) && '' != e.val().Trim())
		{
			var title = e.attr('title');
			showMsg(title + '格式错误!', function(){e.focus()});
			return false;
		}
	}
	return true;
}



/**
 * <description> 打开模式对话框
 * url 超链地址
 * w 宽度
 * h 高度
 * r 是否可设置大小 'yes' or 'no'
 */
function showMd(url, w, h, s, r){
	var scroll = s == undefined ? 'no' : s;
	var resize = r == undefined ? 'yes' : r;
	var property = 'dialogHeight:' + h + 'px;dialogWidth:' + w + 'px;resizable:' + resize + ';help:no;status:no;scroll:' + scroll;
	return window.showModalDialog(url, window, property);
}

/**
 * <description> 打开非模式窗口
 * url 超链地址
 * w 宽度
 * h 高度
 * s 是否显示滚动条
 * r 是否可设置大小 'yes' or 'no'
 */
function openWin(url, w, h, s, r)
{
    var scroll = s == undefined ? 'no' : s;
	var resize = r == undefined ? 'yes' : r;
	var browserheight = $(window).height();//浏览器高度
	var browserwidth = $(window).width();//浏览器宽度
	var property = 'width=' + w + ',height=' + h +',left='+(browserwidth-w)/2+',top='+(browserheight-h)/2+ ',resizable=' + resize + ',scrollbars=' + scroll;
	window.open(url, '', property);
}


//弹出提示信息
function showMsg(msg, func, title)
{
	if(title == undefined || '' == title)
		title = '信息提示';
	if(func == undefined)
	{
		jAlert(msg, title);
	}
	else
	{
		jAlert(msg, title, func);
	}
}

//弹出确认窗口
function showConfirm(msg, func, title)
{
	if(title == undefined || '' == title)
		title = '信息提示';
	if(func == undefined)
	{
		jConfirm(msg, title);
	}
	else
	{
		jConfirm(msg, title, func);
	}
}


//列表的checkbox check所有
//obj为this
//name为checkbox的name
function cbCheck(obj, name)
{
	var cbGroup = $('input:checkbox[name="' + name + '"]');
	var headCb = $(obj);
	var length = cbGroup.length;
	for(var i = 0; i < length; i++)
	{
		var cbx = $(cbGroup.get(i));
		cbx.attr('checked', headCb.attr('checked'));
	}
}


//判断是否有选中checkbox
function hasCheck(name)
{
	var flag = false;
	if(0 == $('input:checkbox[name="'+name+'"][checked]').length){
		showMsg("请先选择记录!");
	}
	else {
		flag = true;
	}
	return flag;
}



//根据file的id获得选中的文件名
function getFileName(fileId)
{
	var file = $('#' + fileId);
	if('' == file.val())
		return '';
	var start = file.val().lastIndexOf('\\') + 1;
	var fileName = file.val().substring(start);
	return fileName;
}



//用户选择,返回list(personId, userName)或user(personId, userName)
function usersSelect(flag)
{
	if(flag == undefined)
		flag = true;
	var url = realPath + '/dept/usersSelect.action?single=' + flag;
	var arr = showMd(url, 800, 600, 'yes');
	return arr;
}

//用户选择,返回list(personId, userName)或user(personId, userName)
function userListSelect(flag)
{
	if(flag == undefined)
		flag = true;
	var url = realPath + '/user/queryUserList.action?single=' + flag;
	var arr = showMd(url, 700, 695, 'yes');
	return arr;
}

//部门选择,返回list(deptId, deptName)或dept(deptId, deptName)
function deptsSelect(flag)
{
	if(flag == undefined)
		flag = true;
	var url = realPath + '/dept/deptsSelect.action?single=' + flag;
	var arr = showMd(url, 400, 450, 'yes');
	return arr;
}

//工程列表选择
function projectSelect()
{
	var url = realPath + '/proMonitor/projectSelect.action';
	var pro = showMd(url, 700, 550, 'yes');
	return pro;
}

//文件格式
function fileFormatSelect()
{
	var url = realPath + '/baseData/queryFileFormat.action';
	var str = showMd(url, 600, 200, 'yes');
	return str;
}




//添加select下拉的项
function addSelectOption(id, data, value, label, select)
{
	dwr.util.removeAllOptions(id);
	var selectControl = $('#' + id);
	if(select == undefined || select == true)
	{
		selectControl.append('<option value="">--请选择--</option>');
	}
	if(data != null)
	{
		dwr.util.addOptions(id, data, value, label);
	}
}

function addSelectOption2(selectControl, data, value, label, select)
{
	selectControl.empty();
	if(select == undefined || select == true)
	{
		selectControl.append('<option value="">--请选择--</option>');
	}
	if(data != null)
	{
		var len = data.length;
		for(var i = 0; i < len; i++)
		{
			selectControl.append('<option value="' + data[i][value] + '">' + data[i][label] + '</option>');
		}
	}
}



//checkbox值转为1,2,3,4的形式
//cbName为checkbox的name
//flag 如果true则为1,2,3 如果false则为'1','2','3'
function groupToString(cbName, flag)
{
	if(flag == undefined)
	{
		flag = true;
	}
	var code = '';
	if(flag == false)
	{
		code = '\'';
	}
	var cbGroup = $('input:checkbox[name="' + cbName + '"]');
	var len = cbGroup.length;
	var str = '';
	for(var i = 0; i < len; i++)
	{
		var obj = $(cbGroup.get(i));
		if(obj.attr('checked'))
		{
			str += ',' + code + obj.val() + code;
		}
	}
	if('' != str)
	{
		str = str.substring(1);
	}
	return str;
}


//多个转来字符串，true为1,2,3 false为'1','2','3'
function multiToString(name, type, flag)
{
	if(flag == undefined)
	{
		flag = true;
	}
	var code = '';
	if(flag == false)
	{
		code = '\'';
	}
	var group = $('input:' + type + '[name="' + name + '"][checked]');
	var len = group.length;
	var str = '';
	for(var i = 0; i < len; i++)
	{
		str += ',' + code + $(group.get(i)).val() + code;
	}
	if('' != str)
	{
		str = str.substring(1);
	}
	return str;
}



/*
* 判断是否为整数，是则返回true,否则返回false
*/
function checkInteger(obj)
{   	
	if (/^(\+|-)?\d+$/.test( obj.val() )) 
	{
	   return true;
	} 
	else 
	{
	    return false;
	}
}

/*
* 判断是否为实数，是则返回true,否则返回false
*/
function checkFloat(obj)
{   	
	if (/^(\+|-)?\d+($|\.\d+$)/.test( obj.val() )) 
	{
	   return true;
	} 
	else 
	{
		return false;
	}
}

/**
 * 把html的input,select,textarea变为只读
 */
function controlReadOnly(){
	var inputRead = document.getElementsByTagName("input"); 
    var inputRead2 = document.getElementsByTagName("textarea");
    var inputRead3 = document.getElementsByTagName("select");
    //alert(inputRead.length);
    for(var i=0 ; i< inputRead.length; i++){
       var obj = inputRead[i];
       obj.onmousemove=function(){ obj.setCapture();};
       obj.onmouseout=function(){obj.releaseCapture();};
       obj.onfocus=function(){obj.blur();};
    }
     for(var i=0 ; i< inputRead2.length; i++){
       var obj = inputRead2[i];
       obj.onmousemove=function(){ obj.setCapture();};
       obj.onmouseout=function(){obj.releaseCapture();};
       obj.onfocus=function(){obj.blur();};
    }
     for(var i=0 ; i< inputRead3.length; i++){
       var obj = inputRead3[i];
       obj.onmousemove=function(){ obj.setCapture();};
       obj.onmouseout=function(){obj.releaseCapture();};
       obj.onfocus=function(){obj.blur();};
    }
}



//获得前一页的url
function getPrePageUrl()
{
	var url = '';
	var parentPage = $('#prePage');
	dwr.engine.setAsync(false);
	sysConfigService.goBack(parentPage.val(), function(data){
		url = realPath + '/' + data;
	});
	dwr.engine.setAsync(true);
	return url;
}


//设置返回参数
//nextPage 下一页的名称
//returnAbled 下一页是否可返回 Y 或 N
//sign 参数连接符 ? 或 &
function setReturnParam(next, returnAbled, sign)
{
	if(sign == undefined || sign == null)
	{
		sign = '?';
	}
	var nextPage = $('#nextPage');
	var url = sign + 'nextPage=' + next + '&returnAbled=' + returnAbled + '&prePage=' + nextPage.val();
	return url;
}

//树形菜单的显示和隐藏(父菜单启用onclick事件，子菜单用tbody标签包住。)
function displayMenu(id,cssName)
{
    var selectObj = $('#'+id);
	var tbodys = $('.'+cssName);
	for(var i = 0; i < tbodys.length; i++)
	{
		var tb = $(tbodys.get(i));
	    if(selectObj.attr('id') != tb.attr('id'))
	    {
			tb.css('display', 'none');
		}
	}
	if(selectObj.css('display') == 'block')
	{
		selectObj.css('display','none');
	}
	else if(selectObj.css('display') == 'none')
	{
		selectObj.css('display','block');
	}
}

//输入长度限制(如input的属性cssClass="lengthLimit" limit="50" title="标题"表示“标题”的输入长度限制50)
function lengthLimit(){
	var limitObjs = $('.lengthLimit');
	for(var i = 0 ; i < limitObjs.length; i++){
		var limitObj = $(limitObjs.get(i));
		var limitLen = limitObj.attr('limit');
		var realLen = limitObj.val().length;
		if(realLen > limitLen){
			alert(limitObj.attr('title') + '长度不能超过' + limitLen);
			limitObj.focus();
			return false;
		}
	}
	return true;
}


//文件下载通用
//fileName:文件名  fileUrl:相对路径  compress:true|false,是否要压缩
function toDownloadFile(fileName, fileUrl, compress)
{
	if(fileName == null || '' == fileName)
	{
		fileName = '未命名';
	}
	if(fileUrl == null || '' == fileUrl)
	{
		showMsg('文件地址出错');
		return;
	}
	var url = realPath + '/common/download.action?fileName=' + fileName + '&url=' + fileUrl;
	if(compress != undefined && compress != null)
	{
		url += '&compress=' + compress;
	}
   	url = encodeURI(encodeURI(url));
   	window.location.href = url;
}

//全屏
function allScreen()
{
	
	if (window.screen)
	{
	   	var myw = screen.availWidth;
	   	var myh = screen.availHeight;
	   	window.moveTo(0, 0);
	   	window.resizeTo(myw, myh);
   	}
}

//菜单导航
function navigationTo(url)
{
	if('' != url)
	{
		window.location.href = realPath + '/' + url;
	}
}

//获得fckeditor的值
function getFckValue(id)
{
	var oEditor = FCKeditorAPI.GetInstance(id);
	return oEditor.EditorDocument.body.innerHTML;
}


function resetSearch()
{
	var searchControl = $('.search');
	var len = searchControl.length;
	for(var i = 0; i < len; i++)
	{
		var obj = $(searchControl.get(i));
		if('text' == obj.attr('type') || 'select-one' == obj.attr('type'))
		{
			obj.val('');
		}
		else if('radio' == obj.attr('type'))
		{
			if('' == obj.val())
			{
				obj.attr('checked', true);
			}
		}
		else if('checkbox' == obj.attr('type'))
		{
			obj.attr('checked', false);
		}
	}
}

function ajaxAction(src, methodType, frmId, isReturn, callBack)
{
	if(isReturn)
	{
		$.ajax({
			url:realPath + '/' + src,
			type:methodType,
			data:$("#" + frmId).serialize(),
			dataType:'json',
			success:callBack
		});
	}
	else
	{
		$.ajax({
			url:realPath + '/' + src,
			type:methodType,
			data:$("#" + frmId).serialize(),
			success:callBack == undefined ? null : callBack
		});
	}
}

function strToDate(time)
{
	var newTime = time.replace(/-/g, "/");
	var date = new Date(Date.parse(newTime));
	return date;
}

function isNotNull(val)
{
	if(val != undefined && val != null && '' != val.Trim())
	{
		return true;
	}
	return false;
}

function getParentWin()
{
	var pWin = window.dialogArguments;
	return pWin;
}

//把日期转为yyyy-MM-dd格式
function toDateStr(date)
{
	var str = date.getFullYear() + '-' + (date.getMonth() + 1) + '-' + date.getDate();
	return str;
}

//保留n位小数
function toNBitFloat(val, n)
{
	if(n <= 0)
	{
		return val;
	}
	var x = 1;
	for(var i = 0; i < n; i++)
	{
		x = x * 10;
	}
	return Math.round(val * x) / x;
}


//new grid
function newJqGrid(obj)
{
	if(!isNotNull(obj.gridId))
	{
		showMsg('gridId不能为空。');
		return;
	}
	if(!isNotNull(obj.url))
	{
		showMsg('url不能为空。');
		return;
	}
	if(obj.head == null)
	{
		showMsg('head不能为空。');
		return;
	}
	if(obj.column == null)
	{
		showMsg('column不能为空。');
		return;
	}
	var newWidth = obj.width == null ? 700 : obj.width;
	var newHeight = obj.height == null ? 300 : obj.height;
	var newHasCb = obj.hasCb == null ? false : obj.hasCb;
	var newTitle = obj.title == null ? '' : obj.title;
	$('#' + obj.gridId).jqGrid({
        datatype:'json',
        mtype:'POST',
        url:realPath + '/' + obj.url,
        colNames:obj.head,
        colModel:obj.column,
        pager:obj.pagerId,
        width:newWidth,
        height:newHeight,
        rowNum:15,
        rowList:[5,15,25,50],
        prmNames: {
        	page:'pager.thisPage',
        	rows:'pager.pageSize',
        	sort:'pager.sortField',
        	order:'pager.sortType'
        },
        jsonReader : obj.jsonReader == null ? {
     	root: 'list',
     	page: 'pager.thisPage',
     	total: 'pager.pageCount',
     	records: 'pager.total',
     	repeatitems: false,
     	id: obj.id == null ? 'id' : obj.id} : obj.jsonReader,
        viewrecords:true,
        gridview:true,
        multiselect:newHasCb,
        caption: newTitle,
        onSelectRow: obj.rowClick
    });
}

//jqGrid search
function toSearchList(gridId, searchJson)
{
	if(isNotNull(gridId))
	{
		if(gridId.indexOf('#') > -1)
		{
			gridId = gridId.substring(1);
		}
	}
	else
	{
		showMsg('查询不正确。');
		return;
	}
	if(searchJson == undefined)
	{
		searchJson = {};
	}
	$("#" + gridId).jqGrid().setGridParam({
    	postData: searchJson
    }).trigger("reloadGrid", [{page:1}]);
}

//body宽,除去滚动条
function getBodyWidth()
{
	return $(window).width() - 5;
}

function gridAutoWidth(gridId, pId)
{
	var width = 700;
	if(pId == 'win')
	{
		width = getBodyWidth();
	}
	else
	{
		var pControl = $('#' + pId);
		width = pControl.width() - 5;
	}
	$("#" + gridId).jqGrid('setGridWidth', width);
}

//数组包含值
function arrayInclude(arr, val)
{
	var len = arr.length;
	for(var i = 0 ; i < len; i++)
	{
		if(arr[i] == val)
		{
			return true;
		}
	}
	return false;
}

function showDivDesc(id, msg, position)
{
	position = position == undefined ? 'top' : position;
	var divDesc = $('#divDesc');
	var control = $('#' + id);
	var ht = msg;
	divDesc.html(ht);
	var divHeight = divDesc.height();
	var left = control.offset().left;
	var top = control.offset().top;
	var divTop = top - divHeight - 2;
	
	divDesc.css({'display':'block', 'left':left, 'top':divTop, 'z-index':100});
}

function hideDivDesc()
{
	var divDesc = $('#divDesc');
	divDesc.css('display', 'none');
}


